
# 写一个类 MyMatrix,  实现矩阵的显示，矩阵的加法。
# class MyMatrix:
#     ...
# m1 = MyMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# m2 = MyMatrix([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
# print(m1)  # 重写 __str__(self) 方法
# # | 1 2 3 |
# # | 4 5 6 |
# # | 7 8 9 |
# m3 = m1.add(m2)  # 矩阵相加 add(self, other)
# print(m3)
# # | 11 22 33 |
# # | 44 55 66 |
# # | 77 88 99 |


class MyMatrix:
    def __init__(self, matrix_data):
        # 1. 共用列表没有复制
        # self.data = matrix_data
        # 2. 写代码实现深考备
        L = []  # 准备复制列表
        for a_list in matrix_data:
            inner_list = []
            # 复制最内层的列表
            for anumber in a_list:
                inner_list.append(anumber)
            L.append(inner_list)
        self.data = L

    def __str__(self):
        '''
        # | 1 2 3 |
        # | 4 5 6 |
        # | 7 8 9 |
        '| 1 2 3 |\n| 4 5 6 |\n| 7 8 9 |'
        '''
        # 第一步二维列表转为 一维的字符串，即将
        #  [[1, 2, 3],
        #   [4, 5, 6],
        #   [7, 8, 9]]
        #  转为 L2 :
        #  ['| 1 2 3 |',
        #   '| 4 5 6 |',
        #   '| 7 8 9 |']
        L2 = []
        for a_list in self.data:
            a_str = ' '.join([str(x) for x in a_list])  # '1 2 3'
            a_str = '| ' + a_str + ' |'
            L2.append(a_str)
        # print(L2)
        return '\n'.join(L2)

    def add(self, other):
        # result = [[11, 22, 33], [44, 55, 66], [77, 88, 99]]
        result = []  # 创建一个新的列表
        for row_index in range(len(self.data)):
            # row_index 表示行索引 0, 1, 2
            # 创建一个内部的列表 inner_list
            inner_list = []
            for col_index in range(len(self.data[row_index])):
                anumber = self.data[row_index][col_index] + other.data[row_index][col_index]
                inner_list.append(anumber)
            result.append(inner_list)
        return MyMatrix(result)

L1 =  [[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]]
m1 = MyMatrix(L1)
m2 = MyMatrix([[10, 20, 30],
               [40, 50, 60],
               [70, 80, 90]])
print(m1)  # 重写 __str__(self) 方法
# L1[0][1] = 200
# print(m1)
# | 1 2 3 |
# | 4 5 6 |
# | 7 8 9 |
# '''| 1 2 3 |\n| 4 5 6 |\n| 7 8 9 |'''
print(m2)
m3 = m1.add(m2)  # 矩阵相加 add(self, other)
print(m3)  # None
# | 11 22 33 |
# | 44 55 66 |
# | 77 88 99 |

L1 = [1, 2, 3]
L2 = [4, 5, 6]
L3 = L1 + L2
print(L3)
